<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';

const totalSpend = ref('35.02');
const totalHours = ref('32h');

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

onMounted(() => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
    xAxis: {
      type: 'category',
      data: [
        '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00',
      ],
      axisLine: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        name: 'Usage',
        type: 'bar',
        data: [10, 20, 30, 25, 30, 20, 25, 30, 20, 30],
        itemStyle: {
          borderRadius: [10,10,0,0], // 设置圆角半径
          color: ({ dataIndex }: { dataIndex: number }) => {
                if (dataIndex === 2) {
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#aaf7ff' },
                    { offset: 1, color: '#e5c1ff' },
                  ]);
                }
                return '#333';
          },
        },
      },
    ],
  };

  chartInstance.setOption(option);

  // 监听窗口大小变化并调整图表大小
  window.addEventListener('resize', resizeHandler);

  function resizeHandler() {
    if (chartInstance) {
      chartInstance.resize();
    }
  }

  // 初始化时手动触发一次resize以适应初始容器大小

    resizeHandler();
});

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', () => chartInstance?.resize());
    chartInstance.dispose();
  }
});
</script>

<template>
  <div class="usage-status-chart">
    <div class="chart-head">
      <span>Usage Status</span>
    </div>

    <div class="chart-data">
      <div>
        <span>Total spend</span>
        <span>{{totalSpend}}KwH</span>
      </div>
      <div>
        <span>Total hours</span>
        <span>{{ totalHours }}h</span>
      </div>
    </div>
    <div class="chart-container" ref="chartRef"></div>
  </div>
</template>

<style lang="scss" scoped>
.usage-status-chart {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;

  .chart-head span {
    font-size: 20px;
    color: white;
  }

  .chart-data {
    display: flex;
    gap: 150px;

    div {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    div span:first-child {
      color: rgb(83, 83, 83);
    }

    div span:last-child {
      color: white;
      font-size: 19px;
    }
  }

  .chart-container {
    width: 100%;
    height: 200px;
  }
}
</style>
